package fischl.huyaApi;

import com.google.gson.reflect.TypeToken;
import fischl.Global;
import fischl.log.Log;
import fischl.log.LogFactory;
import okhttp3.Request;
import okhttp3.Response;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

public class VideoTimeUtil {
  private static final Log log = LogFactory.get("timeUtil");


  public static long[] getTime(String vid) {
    String url = "https://liveapi.huya.com/moment/getMomentContent?videoId=" + vid + "&uid=&_=" + System.currentTimeMillis();
    Type type = TypeToken.getParameterized(HuyaApiResponse.class, Data.class).getType();
    Request request = new Request.Builder().get().url(url).build();

    try {
      Response response = Global.okHttpClient().newCall(request).execute();
      if (!response.isSuccessful() || response.body() == null) {
        log.e("Unable get time for vid {}, request failed", vid);
        return null;
      }
      String json = response.body().string();
      HuyaApiResponse<Data> data = Global.gson().fromJson(json, type);
      List<Definitions> list = data.data.moment.videoInfo.definitions;
      String s = list.get(0).url;
      String dataPair = s.substring(s.lastIndexOf('/') + 1, s.lastIndexOf(".m3u8?"));
      String[] s1 = dataPair.split("_");
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss", Locale.CHINA);
      long[] result = new long[2];
      result[0] = format.parse(s1[0]).getTime();
      result[1] = format.parse(s1[1]).getTime();
      return result;
    } catch (Exception e) {
      log.e("unable get time for vid: " + vid, e);
    }
    return null;
  }

  public static class HuyaApiResponse<T> {
    public int status;
    public String message;
    public T data;
  }

  public static class Data {
    public Moment moment;
  }

  public static class Moment {
    public VideoInfo videoInfo;
  }

  public static class VideoInfo {
    public List<Definitions> definitions;
  }

  public static class Definitions {
    public String url;
    public String m3u8;
  }
}
